package com.shengqin.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.shengqin.pojo.student.StudentImportParam;
import com.shengqin.service.IStudentService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class StudentDataListener implements ReadListener<StudentImportParam> {

    private final List<StudentImportParam> cachedDataList = new ArrayList<>();

    private IStudentService studentService;

    public StudentDataListener(IStudentService stdService) {
        this.studentService = stdService;
    }

    /**
     */
    public StudentDataListener() {

    }

    @Override
    public void invoke(StudentImportParam data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        if(data.getSex().equalsIgnoreCase("男")){
            data.setSex("1");
        } else if(data.getSex().equalsIgnoreCase("女")){
            data.setSex("2");
        }
        cachedDataList.add(data);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        studentService.importBatch(cachedDataList);
        log.info("存储数据库成功！");
    }
}